using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace net.notdot.Attercop
{
    [Serializable()]
    public class PingMessage : HelloMessage
    {
        private static Random rand = new Random();
        
        public readonly int PingId;

        static PingMessage() { ClientInstance.AddMessageHandler<PingMessage>(); }

        public PingMessage(MessageAddressing addressing, Peer p) : base(addressing, p)
        {
            PingId = rand.Next();
        }

        protected PingMessage(MessageReader reader)
            : base(reader)
        {
            reader.BeginRegion();
            reader.ReadByte();  //Version
            PingId = reader.ReadInt32();
            reader.EndRegion();
        }

        public override void Serialize(MessageWriter writer)
        {
            base.Serialize(writer);

            writer.BeginRegion();
            writer.Write((byte)0);  //Version
            writer.Write(PingId);
            writer.EndRegion();
        }

        public override void Handle(ClientInstance c)
        {
            base.Handle(c);

            //Send them a pong message.
            PongMessage pong = new PongMessage(new MessageAddressing(c.LocalPeer.Address, this.Addressing.From), PingId);
            c.SendMessage(pong);
        }
    }
}
